import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import Small from './small';
import BackRouter from '@/pages/CapacityStudy/KnowledgeSmartMaintenance/backRouter';
import { FormattedMessage } from 'umi-plugin-react/locale';
import { Row, Col, Card, Icon, Tooltip, Form, Button, Input, Spin, Table, message, InputNumber, Drawer, Progress, Modal } from 'antd';
import styles from './index.less';
import tableDataCheck from '@/utils/isBackPrevPage';

const FormItem = Form.Item;

class CheckList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      login: false,
      totala: 0,
      page: 1,
      pageSize: 10,
      similarList: [],
      query: '', // 搜索的关键词
      minWordCount: '', // 最小字数
      maxWordCount: '', // 最大字数
      minAskCount: '', // 最小询问次数
      maxAskCount: '', // 最大询问次数
      order: 'wordCount', // 排序字段
      sort: 'asc', //  排序方式，asc：升序，desc：降序,
      dxList: [],
      selectedRowKeys: [],
      Drawera: false,
      DrawerNoLogin: false,
      percent: 0,
      num: 0,
      timer: null,
    };
  }

  componentDidMount() {
    this.knowledgeQuestionList();
  }

  knowledgeQuestionList = () => {
    const { dispatch, currentUser } = this.props;
    const { page, pageSize, query, minWordCount, maxWordCount, minAskCount, maxAskCount, order, sort } = this.state;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'knowledgeSmartMaintenance/knowledgeQuestionList',
        payload: {
          query, minWordCount, maxWordCount, minAskCount, maxAskCount,
          order, sort, current: page, size: pageSize,
        },
        callback: res => {
          this.setState({ similarList: res.records, totala: res.total, login: false });
        },
      });
    });
  };

  pageWay = a => {
    this.setState({ page: a, dxList: [], selectedRowKeys: [] }, () => {
      this.knowledgeQuestionList();
    });
  };

  onShowSizepageWay = (a, b) => {
    this.setState({ page: a, pageSize: b }, () => {
      this.knowledgeQuestionList();
    });
  };

  // 表单数据
  userInfo = () => {
    return this.props.form.getFieldsValue();
  };

  // 删除回调
  knowledgeQuestionDelete = (ids, url) => {
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: url,
        payload: { ids },
        callback: res => {
          message.success(`${res.msg}`);
          //判断是否需要加载上一页数据 2022.4.8
          const { similarList, page } = this.state;
          const newCurrent = tableDataCheck(similarList, page, ids);
          // console.log(newCurrent, similarList, page, ids);
          this.setState({ login: false, selectedRowKeys: [], dxList: [], page: newCurrent }, () => {
            this.knowledgeQuestionList();
          });
        },
      });
    });
  };

  // 引导黑名单回调
  knowledgeQuestionDelete = (ids, url) => {
    if (ids.length === 0) {
      message.error('请先选择需要操作内容');
    } else {
      const { dispatch, currentUser } = this.props;
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: url,
          payload: { ids },
          callback: res => {
            message.success(`${res.msg}`);
            //判断是否需要加载上一页数据 2022.4.8
            const { similarList, page } = this.state;
            const newCurrent = tableDataCheck(similarList, page, ids)
            this.setState({ login: false, selectedRowKeys: [], dxList: [], page: newCurrent }, () => {
              this.knowledgeQuestionList();
            });
          },
        });
      });
    }
  };

  deleteTable = item => {
    this.setState({ login: true });
    this.knowledgeQuestionDelete(Array(item.id), 'knowledgeSmartMaintenance/knowledgeQuestionDelete');
  };

  deleteTables = item => {
    this.setState({ login: true });
    this.knowledgeQuestionDelete(Array(item.id), 'knowledgeSmartMaintenance/questionBlacklistMoveIn');
  };

  handleOpen = item => { };

  // 批量删除
  batchDelete = () => {
    const { dxList } = this.state;
    this.knowledgeQuestionDelete(dxList, 'knowledgeSmartMaintenance/knowledgeQuestionDelete');
  };

  // 全部删除
  allBatchDelete = () => {
    Modal['confirm']({
      title: '删除任务',
      content: '确定全部删除吗？',
      okText: '删除',
      cancelText: '取消',
      onOk: () => {
        const { dispatch, currentUser } = this.props;
        this.reqRef = requestAnimationFrame(() => {
          dispatch({
            type: 'knowledgeSmartMaintenance/knowledgeQuestionClear',
            payload: { isBlacklist: false },
            callback: res => {
              message.success(`${res.msg}`);
              this.setState({ page: 1 }, () => {
                this.knowledgeQuestionList();
              })
            },
          });
        });
      },
      onCancel() { },
    });
  };

  // 批量移到黑名单
  moveBlacklist = () => {
    const { dxList } = this.state;
    this.knowledgeQuestionDelete(dxList, 'knowledgeSmartMaintenance/questionBlacklistMoveIn');
  };

  backRouter = () => {
    const { dispatch } = this.props;
    dispatch(routerRedux.push({ pathname: '/capacity/knowledgeSmartMaintenance' }));
  };

  // 查询
  theQuery = () => {
    let user = this.userInfo();
    this.setState(
      {
        query: user.inputA,
        page: 1,
        minWordCount: user.InputNumber1,
        maxWordCount: user.InputNumber2,
        minAskCount: user.InputNumber3,
        maxAskCount: user.InputNumber4,
      },
      () => {
        this.knowledgeQuestionList();
      }
    );
  };

  // 排序
  pXhandleChange = (pagination, filters, sorter) => {
    if (sorter.field === 'wordCount') {
      // 字数排序
      if (sorter.order === 'ascend') {
        // 升序
        this.setState({ order: 'wordCount', sort: 'asc' }, () => {
          this.knowledgeQuestionList();
        });
      };
      if (sorter.order === 'descend') {
        // 降序
        this.setState({ order: 'wordCount', sort: 'desc' }, () => {
          this.knowledgeQuestionList();
        });
      }
    };
    if (sorter.field === 'askCount') {
      // 询问次数排序
      if (sorter.order === 'ascend') {
        // 升序
        this.setState({ order: 'askCount', sort: 'asc' }, () => {
          this.knowledgeQuestionList();
        });
      };
      if (sorter.order === 'descend') {
        // 降序
        this.setState({ order: 'askCount', sort: 'desc' }, () => {
          this.knowledgeQuestionList();
        });
      }
    }
  };

  // ---- 抽屉弹框-----
  showDrawer = () => {
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'knowledgeSmartMaintenance/knowledgeQuestionChatStatus',
        payload: {},
        callback: res => {
          const result = res;
          if (res.status == 'none') {
            const { dispatch, currentUser } = this.props;
            this.reqRef = requestAnimationFrame(() => {
              dispatch({
                type: 'knowledgeSmartMaintenance/knowledgeQuestionChatSubmit',
                payload: {},
                callback: res => {
                  if (res.code === 0) {
                    this.setState({ taskId: result.taskId }, () => {
                      this.showDrawer();
                    });
                  }
                },
              });
            });
          };
          if (res.status === 'wait') {
            this.setState({ visiblea: true, DrawerNoLogin: false }, () => {
              this.percent();
            });
          };
          if (res.status === 'success' && this.state.num === 0) {
            this.setState({ visiblea: true, DrawerNoLogin: true });
          };
          if (res.status === 'success' && this.state.num === '1.0') {
            this.setState({ DrawerNoLogin: true, num: 0 });
          }
        },
      });
    });
  };

  // 进度条任务
  percent = () => {
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'knowledgeSmartMaintenance/knowledgequestionChatProcess',
        payload: { taskId: this.state.taskId },
        callback: res => {
          if (res.process === '1.0') {
            this.setState({ num: res.process }, () => {
              this.showDrawer();
            });
          } else if (res.process === 0) {
            this.setState({ percent: res.process }, () => {
              this.state.timer = setTimeout(() => {
                this.percent();
              }, 1000);
            });
          } else {
            const number = res.process;
            this.setState({ percent: Math.floor(Number(number * 100)) }, () => {
              this.state.timer = setTimeout(() => {
                this.percent();
              }, 500);
            });
          }
        },
      });
    });
  };

  onClose = () => {
    this.setState({ visiblea: false }, () => {
      const { timer } = this.state;
      if (timer) {
        clearTimeout(timer);
      }
    });
  };

  // 子组件回调
  gress = (a, taskId) => {
    if (a === 0) {
      this.setState({ taskId }, () => {
        this.showDrawer();
      });
    }
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        let a = [];
        selectedRows.map((item, index) => {
          a.push(item.id);
        });
        this.setState({ dxList: a, selectedRowKeys });
      },
    };
    const columns = [
      {
        title: '问题',
        width: 'calc(30vw)',
        dataIndex: 'question',
        render(item) {
          return (
            // <div className={styles.wtbj}>{item}</div>
            <div dangerouslySetInnerHTML={{ __html: item }} />
          );
        },
      },
      {
        title: '字数',
        width: 'calc(10vw)',
        sorter: (a, b) => { },
        dataIndex: 'wordCount',
      },
      {
        title: '询问次数',
        dataIndex: 'askCount',
        sorter: (a, b) => { },
        width: 'calc(10vw)',
      },
      {
        title: '操作',
        width: 'calc(15vw)',
        render: (text, item) => {
          return (
            <div className={styles.flexBj}>
              <div
                style={{ marginRight: 10, marginBottom: 4 }}
                className={styles.buttongl}
                onClick={() => this.deleteTable(item)}
              >
                <span>
                  <Icon size="small" type="delete" style={{ marginRight: 5 }} />
                </span>
                <span>删除</span>
              </div>

              <div
                style={{ marginRight: 10, marginBottom: 4 }}
                className={styles.buttong2}
                onClick={() => this.deleteTables(item)}
              >
                <span style={{ whiteSpace: 'nowrap' }}>
                  <Icon size="small" type="user-delete" style={{ marginRight: 5 }} />
                </span>
                <span style={{ whiteSpace: 'nowrap' }}>转移到黑名单</span>
              </div>
            </div>
          );
        },
      },
    ];

    return (
      <Suspense fallback={<PageLoading />}>
        <PageHeaderWrapper>
          <div style={{ minHeight: 'calc(100vh - 150px)', background: '#ffffff' }}>
            <Row className={styles.colorBackground}>
              <Col style={{ padding: 10 }} xs={24}>
                <span className={styles.title}>
                  <span>问题库</span>
                  <BackRouter pathname="/capacity/knowledgeSmartMaintenance"></BackRouter>
                </span>
              </Col>
            </Row>
            <Card bordered={false}>
              <Row>
                <Form style={{ marginBottom: 20 }} className={styles.clearfix} layout="inline">
                  <FormItem>
                    {getFieldDecorator('inputA', { initialValue: '', })(
                      <Input onPressEnter={() => this.theQuery()} placeholder="多个关键词空格隔开" style={{ width: 200 }} />
                    )}
                  </FormItem>
                  <FormItem>
                    <div>
                      <span style={{ marginRight: 10 }}>字数</span>
                      {getFieldDecorator('InputNumber1', { initialValue: '', })(
                        <InputNumber min={0} max={100} placeholder="最小值" style={{ width: 90 }} />
                      )}
                      <span style={{ margin: '0px 10px' }}>—</span>
                      {getFieldDecorator('InputNumber2', { initialValue: '', })(
                        <InputNumber min={0} max={100} placeholder="最大值" style={{ width: 90 }} />
                      )}
                    </div>
                  </FormItem>
                  <FormItem>
                    <div>
                      <span style={{ marginRight: 10 }}>询问次数</span>
                      {getFieldDecorator('InputNumber3', { initialValue: '', })(
                        <InputNumber min={0} max={100} placeholder="最小值" style={{ width: 90 }} />
                      )}
                      <span style={{ margin: '0px 10px' }}>—</span>
                      {getFieldDecorator('InputNumber4', { initialValue: '', })(
                        <InputNumber min={0} max={100} placeholder="最大值" style={{ width: 90 }} />
                      )}
                    </div>
                  </FormItem>
                  <FormItem className="zdyButtonZ">
                    <Button onClick={this.theQuery} type="primary" icon="search">查询</Button>
                  </FormItem>
                  <span style={{ float: 'right' }}>
                    <FormItem className="zdyButtonA">
                      <Button onClick={this.batchDelete} type="primary">
                        批量删除
                      </Button>
                    </FormItem>
                    <FormItem className="zdyButtonD">
                      <Button onClick={this.allBatchDelete} type="primary">
                        全部删除
                      </Button>
                    </FormItem>
                    <FormItem className="zdyButtonB">
                      <Button onClick={this.moveBlacklist} type="primary">
                        移到黑名单
                      </Button>
                    </FormItem>
                    <FormItem className="zdyButtonC">
                      <Button onClick={this.showDrawer} type="primary">
                        清除闲聊问题
                      </Button>
                    </FormItem>
                  </span>
                </Form>
                <Spin spinning={this.state.login}>
                  <Table
                    className="zdyTable"
                    rowSelection={rowSelection}
                    onChange={this.pXhandleChange}
                    columns={columns}
                    dataSource={this.state.similarList} // 数据
                    // onChange={this.handleChange}
                    pagination={{
                      // 分页
                      total: this.state.totala,
                      pageSize: this.state.pageSize, // 显示几条一页
                      current: this.state.page, // 当前页
                      showSizeChanger: true, // 是否显示可以设置几条一页的选项
                      showQuickJumper: true,
                      onChange: this.pageWay,
                      onShowSizeChange: this.onShowSizepageWay,
                    }}
                    rowKey="id"
                  />
                </Spin>
              </Row>
            </Card>
            <Drawer
              width="900"
              title="清除闲聊问题"
              placement="right"
              onClose={this.onClose}
              visible={this.state.visiblea}
            >
              {this.state.DrawerNoLogin ? (
                <Small
                  ProgressName={this.state.visiblea}
                  gress={this.gress}
                  taskId={this.state.taskId}
                />
              ) : (
                <div
                  className={styles.progrees}
                  style={{ minHeight: 'calc(100vh - 150px)', background: '#ffffff' }}
                >
                  <div className={styles.center} style={{ color: '#000', width: 169 }}>
                    <span>正在智能识别闲聊知识库</span>
                    <span className={styles.loading}></span>
                  </div>
                  <div style={{ height: 30 }}></div>
                  <Progress type="circle" percent={this.state.percent} width={90} strokeWidth={8} />
                  <div style={{ height: 30 }}></div>
                  <Button onClick={this.onClose} type="primary">关闭</Button>
                </div>
              )}
            </Drawer>
          </div>
        </PageHeaderWrapper>
      </Suspense>
    );
  }
}

export default connect(({ user }) => ({
  // 全局数据
  currentUser: user.currentUser,
}))(Form.create()(CheckList));
